package com.lj.queue;

import com.lj.common.module.ModuleInfo;
import com.lj.queue.properties.DelayQueueProperties;
import jakarta.annotation.Resource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author luojing
 * @since 2025/7/16 18:01
 */
@Configuration
@ComponentScan("com.lj.queue")
@MapperScan("com.lj.queue.mapper")
public class QueueAutoConfiguration {

    @Resource
    private DelayQueueProperties delayQueueProperties;

    @Bean
    public ModuleInfo queueModuleInfo() {
        return new ModuleInfo().setModuleName("queue");
    }

    /**
     * 仅当容器中不存在名为delayQueueWorker的Bean时生效
     */
    @Bean
    @ConditionalOnMissingBean(name = "delayQueueWorker")
    public ExecutorService delayQueueWorker() {
        return new ThreadPoolExecutor(delayQueueProperties.getWorkerCorePoolSize(),
                delayQueueProperties.getWorkerMaxPoolSize(),
                delayQueueProperties.getKeepAliveTime(),
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "delayWorker-" + threadNumber.getAndIncrement());
                        if (t.isDaemon())
                            t.setDaemon(false);
                        if (t.getPriority() != Thread.NORM_PRIORITY)
                            t.setPriority(Thread.NORM_PRIORITY);
                        return t;
                    }
                });
    }
}